import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:robotcontrol/entity/common_item.dart';
import 'package:robotcontrol/entity/issue_model.dart';
import 'package:robotcontrol/http/http_manager.dart';
import 'package:robotcontrol/http/url.dart';
import 'package:robotcontrol/page/home_page.dart';
import 'package:robotcontrol/utils/tip_util.dart';
import 'package:robotcontrol/utils/toast.dart';
import 'package:robotcontrol/viewmodel/provider_widget.dart';
import 'package:robotcontrol/widgets/appbar.dart';
import 'package:robotcontrol/widgets/banner_widget.dart';
import 'package:robotcontrol/widgets/home_list_item.dart';
const TEXT_HEADER_TYPE = 'textHeader';
class HomeBody extends StatefulWidget {
  @override
  _HomeBodyState createState() => _HomeBodyState();
}

class _HomeBodyState extends State<HomeBody>
    with AutomaticKeepAliveClientMixin {
  //滑动控制器
  // ScrollController _controller = ScrollController();
  RefreshController _refreshController =
  RefreshController(initialRefresh: false);
  bool _isHide = true; //控制加载动画
  List list =[];//请求到的数据
  List banners =[];
  String nextPageUrl; //下一页请求链接
  // @override
  // void dispose() {
  //   _controller.dispose();
  // }

  @override
  void initState() {
    // _controller.addListener(() {
    //   //获得Scrollcontroller监听控件的滑动最大范围
    //   var maxScroll = _controller.position.maxScrollExtent;
    //   // 获得当前位置像素值
    //   var pixels = _controller.position.pixels;
    //   //当前滑动个位置到达底部 同时加载更多数据
    //   if(maxScroll == pixels ){
    //     //加载更多
    //     ToastUtil.toast("sssssssssss");
    //   }
    // });
    //获取第一页数据
    _pullRefresh();
  } //banner数据


  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(
      children: <Widget>[
        //正在加载
        Offstage(
          offstage: !_isHide,
          child: new Center(
            child: CircularProgressIndicator(),
          ), //加载狂
        ),
        //内容
        Offstage(
          offstage: _isHide,
          //下拉刷新控价
          child: SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: true,
            onRefresh: _pullRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              itemCount: list.length + 1,//加上banner 控件
                // controller: _controller,
              //adapter条目item 视图生成方法
                itemBuilder: (BuildContext context, int index) =>
                    _buidItem(index)),
          ),
        )
      ],
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  Widget _buidItem(int index){
    if(0 == index){
      //这里是banner
      return Container(
        padding: EdgeInsets.only(left: 15,top: 15,right: 15),
        height: MediaQuery.of(context).size.height*0.3,//获取屏幕的0.3
        //对子组件进行圆角裁剪
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child:_bannerView() ,
        ),
      );
    }else{
      if(list[index -1].type ==TEXT_HEADER_TYPE){
        return _titleItem(list[index -1]);//时间标题
      }
      return HomeListItemWidget(item: list[index -1]);
    }
    var itemData = list[index -1];
    return Container();
  }
  //列表类型
  //时间类型text
  Widget _titleItem(Item item){
    return Container(
      decoration: BoxDecoration(color:Colors.white24),
      padding: EdgeInsets.only(top: 15,bottom: 15),
      child: Center(
        child: Text(
          item.data.text,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87
          ),
        ),
      ),
    );
  }
  ///banner
  Widget _bannerView(){
    return BannerWidget(list: banners,);
  }

  Future<void> _pullRefresh() {
    _isHide = true;
    HttpManager.getData(Url.feedUrl,
        success: (json){
          IssueEntity result = IssueEntity.fromJson(json);
          nextPageUrl = result.nextPageUrl;
          banners = result.itemList;
          list.clear();
          banners.removeWhere((element) => element.type =="banner2");
          _onLoading();
          setState((){
            _isHide = false;
          });
          _refreshController.refreshCompleted();
        }
    );
    return null;
  }
  _onLoading() {
    if(nextPageUrl == null){
      _refreshController.loadNoData();
      return;
    }
    HttpManager.getData(nextPageUrl,
        success: (json){
          IssueEntity result = IssueEntity.fromJson(json);
          nextPageUrl = result.nextPageUrl;
          result.itemList.removeWhere((element) => element.type =="banner2");
          list.addAll(result.itemList);
          _refreshController.loadComplete();
          setState((){
            _isHide = false;
          });
        }
    );
    return null;
  }
}


